<?php
/**
 * User: aka
 * Time: 20:34
 */

namespace app\read\controller;

use app\validate\users\SignIn;
use think\facade\Session;
use think\Request;

class Users
{
    private $userInfo;

    public function __construct()
    {
        $this->userInfo = null;
    }

    public function __destruct()
    {
        unset($this->userInfo);
    }

    private function saveUserInfoSession($request, $userInfo)
    {
        $saveUserSessionInfo = array();
        $saveUserSessionInfo['id'] = $userInfo['id'];
        $saveUserSessionInfo['email'] = $userInfo['email'];
        $saveUserSessionInfo['game_id'] = $userInfo['game_id'];
        $saveUserSessionInfo['game_state'] = $userInfo['game_state'];
        $saveUserSessionInfo['last_login_time'] = $userInfo['last_login_time'];
        $saveUserSessionInfo['last_login_ip'] = $userInfo['last_login_ip'];
        Session::set('user_info', $saveUserSessionInfo);
        $user = \app\tenno\model\Users::get($userInfo['id']);
        $user->last_login_time = time();
        $user->last_login_ip = $request->ip();
        $user->save();
        return json(['state' => 200]);
    }

    public function signIn(Request $request)
    {
        $validate = new SignIn();
        if (!$validate->check($request->param())) {
            return json($validate->getError());
        }else{
            $this->userInfo = \app\tenno\model\Users::where(
                [
                    'email' => $request->param('account'),
                    'password' => get_encode_password($request->param('password'))
                ]
            )->find();
            if (empty($this->userInfo))
            {
                return json(['state' => 500]);
            }elseif($this->userInfo['delete_state'] == 1)
            {
                return json(['state' => 601]);
            }else{
                return $this->saveUserInfoSession($request, $this->userInfo);
            }
        }
    }
}